import { NextResponse } from 'next/server';
import { SDWebUILauncher } from '@/lib/launcher';
import { SYSTEM_CONFIG } from '@/lib/config';

const launcher = SDWebUILauncher.getInstance();
const SD_BASE_URL = SYSTEM_CONFIG.sdWebUI.baseUrl;

export async function GET(request: Request) {
  try {
    const url = new URL(request.url);
    const type = url.searchParams.get('type');
    
    // 如果请求类型是system-info，返回SD WebUI的系统信息
    if (type === 'system-info') {
      try {
        // 代理请求到SD WebUI的system-info接口
        const response = await fetch(`${SD_BASE_URL}/sdapi/v1/system-info/status?full=true&memory=true&state=true`);
        
        if (!response.ok) {
          throw new Error(`SD WebUI API error: ${response.status} ${response.statusText}`);
        }
        
        const data = await response.json();
        return NextResponse.json(data);
      } catch (error: any) {
        console.error('SD system-info API error:', error);
        return NextResponse.json(
          { 
            error: 'Failed to fetch SD system info',
            detail: error.message,
            timestamp: new Date().toISOString()
          },
          { status: 500 }
        );
      }
    }
    
    // 默认返回本地启动器状态
    const status = launcher.getStatus();
    return NextResponse.json(status);
  } catch (error: any) {
    return NextResponse.json(
      { 
        success: false, 
        error: error.message 
      },
      { status: 500 }
    );
  }
}
